package scriptEngine

import (
	"errors"
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"github.com/dop251/goja"
	"strconv"
)

func ReloadScriptEngine(manufacturer, deviceType string, operateEntity *commEntity.OperateEntity) {
	engine := GetScriptEngine(manufacturer, deviceType, operateEntity.OperateMode)

	if operateEntity.OperateMode == "splitHandler" {
		// 装载脚本
		decode := operateEntity.EngineParam["decode"]
		runScript(decode, engine, operateEntity.MakeServiceKey())

		// 测试脚本
		err := testSplitHandler(engine)
		if err != nil {
			commLogger.Console.Error(err.Error())
		}
	}

	if operateEntity.OperateMode == "keyHandler" {
		// 装载脚本
		decode := operateEntity.EngineParam["decode"]
		runScript(decode, engine, operateEntity.MakeServiceKey())

		// 测试脚本
		err := testKeyHandler(engine)
		if err != nil {
			commLogger.Console.Error(err.Error())
		}
	}
}

func runScript(encode interface{}, engine *goja.Runtime, key string) {
	// 定义一个最终的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
			commLogger.Console.Error(fmt.Sprintf("runScript() 捕获到异常:%v", r))
		}
	}()

	if encode == nil {
		return
	}

	m := encode.(map[string]interface{})
	_, err := engine.RunString(m["code"].(string))
	if err != nil {
		commLogger.Console.Error("初始化脚本引擎异常：" + key + "; " + err.Error())
	}
}

func testSplitHandler(engine *goja.Runtime) (err error) {
	// 定义一个最终的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
			err = errors.New(fmt.Sprintf("testSplitHandler() 捕获到异常:%v", r))
		}
	}()

	// 执行JSP脚本中的函数：getHeaderLength
	encode, ok := goja.AssertFunction(engine.Get("getHeaderLength"))
	if !ok {
		return errors.New("未定义函数：getHeaderLength")
	}

	// 执行函数
	res, err := encode(goja.Undefined())
	if err != nil {
		return err
	}
	_, err = strconv.ParseInt(res.String(), 10, 64)
	if err != nil {
		return err
	}

	// 执行JSP脚本中的函数：getHeaderLength
	_, ok = goja.AssertFunction(engine.Get("getPackLength"))
	if !ok {
		return errors.New("未定义函数：getPackLength")
	}

	// 执行JSP脚本中的函数：getHeaderLength
	_, ok = goja.AssertFunction(engine.Get("isInvalidPack"))
	if !ok {
		return errors.New("未定义函数：isInvalidPack")
	}

	return nil
}

func testKeyHandler(engine *goja.Runtime) (err error) {
	// 定义一个最终的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
			err = errors.New(fmt.Sprintf("testKeyHandler() 捕获到异常:%v", r))
		}
	}()

	// 执行JSP脚本中的函数：getHeaderLength
	_, ok := goja.AssertFunction(engine.Get("getServiceKey"))
	if !ok {
		return errors.New("未定义函数：getServiceKey")
	}

	return nil
}
